#!/bin/sh
export NLS_LANG=AMERICAN_AMERICA.AL32UTF8

version=V3.0.0

FEFMSHOST=$3
FEFMSACCOUNT="fis"
kb_pwd=$2
ora_ip=$4
ora_pwd=$5


fefmsLogFile="upgrade_sqlplus_KB_fis.log"
echo "FEFMS update ${version} for schema fis begin" > ./$fefmsLogFile

echo "FEFMS data migration ${version} for schema fis  begin" > ./$fefmsLogFile
#赋权，默认没有操作权限
cd ./data-migration/ && chmod -R 755 *
#对明文进行加密获取密文密码

#fis schema的配置文件更名移入conf目录
rm -f ./conf/datasource-oracle.yml
cp ../yml/datasource-fis-oracle.yml ./conf/datasource-oracle.yml
cd ./bin
####更新配置文件###
#oracle
sed -i "s|passwdsource|${ora_pwd}|g" ../conf/datasource-oracle.yml
sed -i "s|oracle_ip|${ora_ip}|g" ../conf/datasource-oracle.yml
#kingbase
sed -i "s|passwdtarget|${kb_pwd}|g" ../conf/datasource-oracle.yml
sed -i "s|kb_ip|${FEFMSHOST}|g" ../conf/datasource-oracle.yml

sh startup.sh >/dev/null
sleep 10
#1天
echo -n "doing"
    for i in {1..8640}; do
        dm_process=$(ps -ux|grep java|grep kdts-app | wc -l)
        if [[  ${dm_process} == 0 ]]; then
            echo ""
            echo ">>> kingbase data migration successed <<<"
            break
        else
            echo -n "."
            sleep 10
            if [[  ${i} == 8640 ]];then
               exit 1;
            fi
        fi

    done
echo ""

cd ../..


#统计信息收集
ksql -h ${FEFMSHOST}  -fefmsdb  -p54321 -U${FEFMSACCOUNT} -v ON_ERROR_STOP=1 >>./$fefmsLogFile 2>&1 <<EOF
\o vacuum_fis.sql
SELECT 'VACUUM ANALYZE fis.' || table_name || ';' FROM user_tables;
\o
\q
EOF
#删除前两行表头、最后2行行数
sed -i '1,2d' vacuum_fis.sql
sed -i '$d' vacuum_fis.sql
sed -i '$d' vacuum_fis.sql

ksql -h ${FEFMSHOST}  -fefmsdb  -p54321 -U${FEFMSACCOUNT} -v ON_ERROR_STOP=1 >>./$fefmsLogFile 2>&1 <<EOF
select 'database_update_sqlplus' as msg;
\i ./vacuum_fis.sql
\q
EOF

if [[ `grep -c -i "ERROR" ./$fefmsLogFile` -ne 0 || `grep -c "No such file or directory" ./$fefmsLogFile` -ne 0 || `grep -c "command not found" ./$fefmsLogFile` -ne 0 ]] ; then
  echo $version "FEFMS update fail!"  
  echo "FEFMS UPDATE FAIL!" >> ./$fefmsLogFile
else
  echo $version "FEFMS update success!"
  echo "FEFMS UPDATE SUCCESS!" >> ./$fefmsLogFile
fi
